﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WomanMotion.WebApi.Infrastructure.DataBaseCommon;
using WomanMotion.WebApi.Model.Dtos.Classify;
using WomanMotion.WebApi.Model.Dtos.Match;
using WomanMotion.WebApi.Model.Dtos.Schedule;
using WomanMotion.WebApi.Model.Dtos.Team;
using WomanMotion.WebApi.Model.Dtos.Users;
using WomanMotion.WebApi.Model.Dtos.Watch;
using WomanMotion.WebApi.Model.Entitys;
using WomanMotion.WebApi.Repository.IRepository;
using WomanMotion.WebApi.Repository.Repository;
using WomanMotion.WebApi.Service.IService;
using Match = WomanMotion.WebApi.Model.Entitys.Match;

namespace WomanMotion.WebApi.Service.Service
{
    public class MatchService : BaseCRUDService<Match, MatchVM, UpdateMatchDTO, CreatedMatchDTO>, IMatchService
    {
        private readonly IMatchRepository _matchRepository;
        private readonly IClassifyService _classifyService;

        public MatchService(ILogger<MatchService> logger, IMapper mapper, IMatchRepository matchRepository, IHttpContextAccessor httpContext, IClassifyService classifyService) : base(logger, mapper, matchRepository, httpContext)
        {
            _matchRepository = matchRepository;
            _classifyService = classifyService;
        }

        /// <summary>
        /// 前端获取比赛信息接口
        /// </summary>
        /// <param name="pars"></param>
        /// <returns></returns>
        public async Task<PageViewBase<List<LeadingMatchVM>>> GetLeadingMatchAsync(QueryParameterBase pars)
        {
            //多表连接查询赛程信息
            var res = await this._matchRepository.GetCommonPageListAsync<LeadingMatchVM>(_matchRepository.GetDB().Queryable<Schedule>()
                .LeftJoin<Classify>((sche, twoclass) => sche.Classid == twoclass.Id)
                .LeftJoin<Classify>((sche, twoclass, firstclass) => twoclass.Parentid == firstclass.Id)
                .Select((sche, twoclass, firstclass) =>
            new LeadingMatchVM()
            {
                Id = sche.Id,
                Createdby = sche.Createdby,
                Createdtime = sche.Createdtime,
                Updatedby = sche.Updatedby,
                Updatedtime = sche.Updatedtime,
                Ifdisable = sche.Ifdisable,
                FirstLevelClassid = firstclass.Id,
                FirstLevelClassName = firstclass.Name,
                TwoLevelClassid = twoclass.Id,
                TwoLevelClassName = twoclass.Name,
                Starttime = sche.Starttime,
                Remark = sche.Remark
            }).MergeTable(), pars);
            //遍历赛程 往里面添加比赛信息
            if (res != null && res.Data != null)
            {
                foreach (var item in res.Data)
                {
                    //var matchdata = await this.GetListNavAsync(m => m.Classid == item.TwoLevelClassid);
                    //查询比赛信息
                    var matchdata = await this._matchRepository.GetCommonListAsync<MatchPageVM>(_matchRepository.GetDB().Queryable<Match>()
                    .LeftJoin<Classify>((match, calss) => match.Classid == calss.Id)
                    .LeftJoin<Schedule>((match, calss, sche) => match.Scheduleid == sche.Id)
                    .LeftJoin<Team>((match, calss, sche, teama) => match.Teamaid == teama.Id)
                    .LeftJoin<Team>((match, calss, sche, teama, teamb) => match.Teambid == teamb.Id)
                    .LeftJoin<Watch>((match, calss, sche, teama, teamb, watch) => match.Watchid == watch.Id)
                    .Select((match, calss, sche, teama, teamb, watch) =>
                    new MatchPageVM()
                    {
                        Id = match.Id,
                        Createdby = match.Createdby,
                        Createdtime = match.Createdtime,
                        Updatedby = match.Updatedby,
                        Updatedtime = match.Updatedtime,
                        Ifdisable = match.Ifdisable,
                        Classid = match.Classid,
                        Scheduleid = match.Scheduleid,
                        Starttime = match.Starttime,
                        Teamaid = match.Teamaid,
                        Teambid = match.Teambid,
                        Teamascore = match.Teamascore,
                        Teambscore = match.Teambscore,
                        Watchid = match.Watchid,
                        Remark = sche.Remark,
                        ClassName = calss.Name,
                        TeamaName = teama.Name,
                        TeamaLogo = teama.Logo,
                        TeambName = teamb.Name,
                        TeambLogo = teamb.Logo,
                        WatchName = watch.Name,
                        WatchLogo = watch.Logo
                    }).MergeTable().Where(m => m.Ifdisable == 1 && m.Scheduleid == item.Id));
                    item.children = matchdata;
                }
            }

            return res;
        }

        /// <summary>
        /// 获取距离现在日期最近的赛程信息
        /// </summary>
        /// <returns></returns>
        public async Task<Schedule> GetLatelyScheduleAsync(long topLevelId, long twoLevelId)
        {
            DateTime date = DateTime.Now;
            string datatimestr = date.ToString("yyyyMMddHHmmss");
            if (topLevelId == 0 && twoLevelId == 0)
            {
                var res = await _matchRepository.GetDB().Queryable<Schedule>().OrderBy(o => SqlFunc.Abs(Convert.ToInt64(datatimestr) - Convert.ToInt64(o.Starttime.ToString("yyyyMMddHHmmss"))), OrderByType.Asc).FirstAsync();
                return res;
            }
            else if (topLevelId != 0 && twoLevelId == 0)
            {
                //查询出所有下级分类
                var classify = await _classifyService.GetListAsync(m => m.Ifdisable == 1 && m.Parentid == topLevelId);
                var twoclassifyid = classify.Select(m => m.Id).ToList();
                var res = await _matchRepository.GetDB().Queryable<Schedule>().Where(m => twoclassifyid.Contains(m.Classid)).OrderBy(o => SqlFunc.Abs(Convert.ToInt64(datatimestr) - Convert.ToInt64(o.Starttime.ToString("yyyyMMddHHmmss"))), OrderByType.Asc).FirstAsync();
                return res;
            }
            else
            {
                var res = await _matchRepository.GetDB().Queryable<Schedule>().Where(m => m.Classid == twoLevelId).OrderBy(o => SqlFunc.Abs(Convert.ToInt64(datatimestr) - Convert.ToInt64(o.Starttime.ToString("yyyyMMddHHmmss"))), OrderByType.Asc).FirstAsync();
                return res;
            }
        }
    }
}